<template>
<div>
  <div v-show="toggle2">
    <div class="card1">
      <div style="width:100%;background-color:#f2f2f2;height:42px;">
        <span style="margin-left:20px;line-height:42px;">转化漏斗分析</span>
      </div>
    </div>
    <div class="index">
      <div>
        <span style="font-weight:600;">建立漏斗</span>
        <div class="detail" v-for="(options,index) in options1List" :key="'key1'+index">
          <span>
            <el-select v-model="value1List[index]" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.event_code"
                :label="item.event_name"
                :value="item.event_code"
              ></el-option>
            </el-select>
          </span>
          <span>
            <i class="el-icon-plus" style="margin-left:4px;" @click="addOption1"></i>
            <i class="el-icon-minus" style="margin-left:4px;" @click="removeOption1"></i>
          </span>
        </div>
        <el-divider></el-divider>
        <span style="font-weight:600;">过滤条件</span>
        <div class="detail2" v-for="(options,index) in options2List" :key="'key2'+index">
          <span>
            <el-select
              v-model="value2List[index]"
              placeholder="请选择"
              @change="getDropDownListValue(index)"
            >
              <el-option
                v-for="item in options"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </span>
          <span>等于</span>
          <span>
            <el-select v-model="value3List[index]" placeholder="请选择">
              <el-option
                v-for="item in options3List[index]"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </span>
          <span>
            <i class="el-icon-plus" style="margin-left:4px;" @click="addOption2"></i>
            <i class="el-icon-minus" style="margin-left:4px;" @click="removeOption2"></i>
          </span>
        </div>

        <div style="text-align:right;">
          <el-button
            style="width:68px;background-color:#ff8b2f;color:#fff;border-radius:40px;"
            @click="hopperAnalysis"
          >查询</el-button>
        </div>
      </div>
    </div>
    <div style="margin:20px 0 0 0;padding:30px 40px 0 40px;background-color:#fff;height:100%;">
      <div class="block" style="float:left;">
        <el-date-picker
          v-model="dateValue"
          value-format="yyyy-MM-dd"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </div>
      <div style="float:left;margin-left:60px;">
        <el-radio-group v-model="radio1" size="small" @change="changeTheme">
          <el-radio-button label="转化"></el-radio-button>
          <el-radio-button label="转化趋势"></el-radio-button>
        </el-radio-group>
        <span>
          <el-select v-model="optionsValue" placeholder="总体 的 转化率" size="small" @change="initLineOption">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </span>
      </div>
      <div style="float:right;">
        <el-radio-group v-model="radio2" @change="toggleMethod1">
          <el-radio-button :label="1">
            <img :src="img4" style="width:12px;height:12px;" />
          </el-radio-button>
          <el-radio-button :label="2">
            <img :src="img5" style="width:12px;height:12px;" />
          </el-radio-button>
        </el-radio-group>
      </div>
      <div v-show="toggle1" id="main" style="width: 1000px;height:400px;margin-top:10%;" />
      
      <el-table
        v-show="!toggle1"
        :data="tableData1"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <!-- <el-table-column prop="name" label width="240"></el-table-column> -->
        <el-table-column v-for="(column,index) in tableData1Head" :key="index" :prop="column.prop" :label="column.label" width="180">
          <template slot-scope="{row}">
            <div v-if="Array.isArray(row[column.prop])">
              <p v-for="(status, index) in row[column.prop]" :key="index">{{status}}</p>
            </div>
            <span v-else>{{row[column.prop]}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <div  v-show="!toggle2">
   <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用户列表" name="first">
            <div style="text-align:right;">
          <el-button
            style="width:68px;background-color:#ff8b2f;color:#fff;border-radius:40px;"
            @click="toggleMethod2"
          >返回</el-button>
        </div>
          <p style="text-align:left;font-size:8px;">
            <i class="el-icon-warning"></i>
            <span>用户列表抽样展示部分用户用于进一步细查单用户行为，仅展示具有用户属性的用户（需通过SDK上报），最多1000条</span>
          </p>
          <el-table :data="tableData2" style="width: 100%" max-height="800"
            :default-sort="{prop: 'date', order: 'descending'}">
            <el-table-column v-for="(column,index) in tableData2Head" :key="index" :prop="column.prop" :label="column.label" sortable width="120"></el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </el-tab-pane>
      </el-tabs> 
  </div>
</div>
</template>

<script>
import echarts from "echarts";

export default {
  name: "ReportContent",
  props: {},
  data() {
    return {
      paramsName:'',
      currentPage:1,
      pageSize:10,
      total:0,
      toggle1:true,
      toggle2:true,
      radio1: "转化",
      radio2: 1,
      img4: require("@/assets/broken.png"),
      img5: require("@/assets/can.png"),
      activeName: "first",
      options: [],
      optionsValue: "",
      options1: [],
      options1List: [],
      value1List: [],
      options2: [],
      options2List: [],
      value2List: [],
      //options3: [],
      options3List: [],
      value3List: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      dateValue: "",
      tableData2Head:[],
      tableData2: [],
      tableData1Head:[],
      tableData1: [],
      option: {
        //color: ["#48abfe", "#00d06e", "#3be294", "#ffdcba"],
        tooltip: {
          //trigger: "axis",
        },
        legend: {
          icon: "rect",
          itemWidth: 20,
          itemHeight: 6,
          bottom: "0%",
          data: [],
        },
        grid: {
          top: "10%",
          left: "3%",
          right: "4%",
          bottom: "25%",
          containLabel: true,
        },
        yAxis: [
          {
            type: "value",
            axisLabel: {
              show: true,
              interval: "auto",
              formatter: "{value} %",
            },
            splitLine: {
              lineStyle: {
                type: "dashed",
                color: "#DDD",
              },
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            show: true,
          },
        ],
        xAxis: [
          {
            type: "category",
            axisLabel: {
              interval: "auto",
              //show: true,
              splitNumber: 15,
              textStyle: {
                fontSize: 12,
                color: "#656565",
              },
            },
            axisLine: {
              show: true,
            },
            axisTick: {
              show: false,
            },
            data: [],
          },
        ],
        series: [],
      },
      respdata: "",
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.getEventList();
    this.getDropDownListKey();
    this.initChart();
  },
  watch: {},
  methods: {
    handleCurrentChange(val){
      //console.log(val)
      this.currentPage = val;
      this.hopperAnalysisDetail();
    },
    toggleMethod1(){
      this.toggle1 = !this.toggle1;
    },
    toggleMethod2(val){
      //console.log(val);
      this.toggle2 = !this.toggle2;
      if(val){
        this.paramsName = val;
        this.currentPage = 1;
        this.hopperAnalysisDetail();
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    hopperAnalysisDetail() {
      var steps = [];
      for(var i=0;i<this.value1List.length;i++){
        if(this.value1List[i]){
          steps.push({
            "eventcode":this.value1List[i]
          });
        }
      }
      var filterParameter = [];
      for(var i=0;i<this.value3List.length;i++){
        if(this.value3List[i]){
          filterParameter.push(this.value3List[i]);
        }
      }
      var params = {
        steps:  JSON.stringify(steps),
        filterParameter: "[" + filterParameter + "]",
        startDate: this.dateValue[0],
        endDate: this.dateValue[1],
        stepNow:this.paramsName,
        pageNo:this.currentPage,
        pageSize:this.pageSize
      };
      
      if (this.paramsName && this.dateValue && steps.length>0 && filterParameter.length>0) {
        this.$http.post(
            "http://8.134.11.223:8080/userprofile-platform/v1/DataAnalysis/hopperAnalysisDetail",
            params
          ).then((res) => {
            if (res) {
              console.log(res.data);
              if (res.data.flag == true) {
                this.initTable2(res.data.data);
              }
            }
          });
      }
    },
    hopperAnalysis() {
      var steps = [];
      for(var i=0;i<this.value1List.length;i++){
        if(this.value1List[i]){
          steps.push({
            "eventcode":this.value1List[i]
          });
        }
      }
      var filterParameter = [];
      for(var i=0;i<this.value3List.length;i++){
        if(this.value3List[i]){
          filterParameter.push(this.value3List[i]);
        }
      }
      var params = {
        steps:  JSON.stringify(steps),
        filterParameter: "[" + filterParameter + "]",
        startDate: this.dateValue[0],
        endDate: this.dateValue[1],
      };
      
      if (this.dateValue && steps.length>0 && filterParameter.length>0) {
        this.$http.post(
            "http://8.134.11.223:8080/userprofile-platform/v1/DataAnalysis/hopperAnalysis",
            params
          ).then((res) => {
            if (res) {
              //console.log(res.data);
              if (res.data.flag == true) {
                this.respdata = res.data.data;
                this.initTable1();
                //this.initOption();
                this.changeTheme(this.radio1);
              }
            }
          });
      }
    },
    initBarOption(){
      this.option.xAxis[0].data=this.respdata.eventNames;
      var respDetails = this.respdata.eventDetails[0]
      var overview = respDetails[respDetails.length-1].overview;
      var barData=[];
      for(var i=0;i<overview.length;i++){
        barData.push(overview[i].users);
      }
      var barSeries = [];
      barSeries.push({
          data: barData,
          type: "bar",
      });
      this.option.series=barSeries;
      //console.log(this.option.series)
      this.chart.setOption(this.option, true);
    },
    initOptions(){
      var respDetails = this.respdata.eventDetails[0]
      var overview = respDetails[respDetails.length-1].overview;
      var option = [];
      for(var i=1;i<overview.length;i++){
        option.push({
           value: overview[i].step,
           name:'第'+(overview[i].step-1)+'步到第'+overview[i].step+'步'
        });
      }
      this.options = option;
      
    },
    initLineOption(){
      console.log(this.optionsValue)
      var xData = [];
      var lineData = [];
      var respDetails = this.respdata.eventDetails[0];
      for(var i=0;i<respDetails.length-1;i++){
        xData.push(respDetails[i].datadate);
        lineData.push(respDetails[i].overview[this.optionsValue-1].rate);
      }
      var lineSeries = [];
      lineSeries.push({
          data: lineData,
          type: "line",
      });
        this.option.xAxis[0].data =xData;
        this.option.series = lineSeries;
        this.chart.setOption(this.option, true);
    },
    initTable1(){
      var tableHead = [];
      var tableData = [];
      var respName = this.respdata.eventNames;
      var respDetails = this.respdata.eventDetails[0];
       //内容
      for(var i=0;i<respName.length;i++){
        tableData.push({
          name:respName[i]
        })
      }
      //表头
      tableHead.push({
        label:"",
        prop:"name"
      });
      for(var i=0;i<respDetails.length-1;i++){
        //表头
        tableHead.push({
          label:respDetails[i].datadate,
          prop:"date"+i
        })
        var overview = respDetails[i].overview;
        //内容
        for(var j=0;j<overview.length;j++){
          var arr = [];
          arr.push(overview[j].users);
          arr.push(overview[j].rate+'%');
          tableData[j]["date"+i]=arr;
        }
      }
      this.tableData1Head = tableHead;
      this.tableData1  = tableData;
     
    },
    initTable2(respdata){
      this.total = respdata.total;
      this.pageSize = respdata.pageSize;
      this.currentPage = respdata.currentPage;
      respdata = respdata.list;
      var tableHead = [];
      var tableData = [];
       //内容
      for(var i=0;i<respdata.length;i++){
        tableData.push({
          userId:respdata[i].userId
        })
        var tagArray = respdata[i].tagArray;
        for(var j=0;j<tagArray.length;j++){
          tableData[i]["col"+j]=tagArray[j].tagId;
        }
      }
      //表头
      tableHead.push({
          label:"用户ID",
          prop:"userId"
        })
      for(var i=0;i<respdata[0].tagArray.length;i++){
        //表头
        tableHead.push({
          label:respdata[0].tagArray[i].tagName,
          prop:"col"+i
        })
        
      }
      this.tableData2Head = tableHead;
      this.tableData2  = tableData;
     
    },
    getEventList() {
      this.$http
        .post(
          "http://8.134.11.223:8080/userprofile-platform/v1/DataAnalysis/eventList",
          {}
        )
        .then((res) => {
          if (res) {
            var respdata = res.data.data;
            this.options1 = respdata;
            this.addOption1();
          }
        });
    },
    getDropDownListKey() {
      this.$http
        .post(
          "http://8.134.11.223:8080/userprofile-platform/v1/DataAnalysis/dropDownListKey",
          {}
        )
        .then((res) => {
          if (res) {
            var respdata = res.data.data;
            this.options2 = respdata.list;
            this.addOption2();
          }
        });
    },
    getDropDownListValue(index) {
      if (this.value2List[index] != "") {
        this.$http
          .post(
            "http://8.134.11.223:8080/userprofile-platform/v1/DataAnalysis/dropDownListValue?level_2_name=" +
              this.value2List[index],
            { level_2_name: this.value2List[index] }
          )
          .then((res) => {
            if (res) {
              var respdata = res.data.data.list;
              var option = [];
              for (var i = 0; i < respdata.length; i++) {
                option.push({
                  value: JSON.stringify(respdata[i]),
                  name: respdata[i].name,
                });
              }
              //this.options3List[index] = option;
              this.$set(this.options3List, index, option);
              this.value3List[index] = "";
            }
          });
      } else {
        this.options3List[index] = "";
        this.value3List[index] = "";
      }
    },
    addOption1() {
      this.options1List.push(this.options1);
      this.value1List.push("");
    },
    removeOption1() {
      if (this.options1List.length > 1) {
        this.options1List.pop();
        this.value1List.pop();
      }
    },
    addOption2() {
      this.options2List.push(this.options2);
      this.value2List.push("");
      this.options3List.push("");
      this.value3List.push("");
    },
    removeOption2() {
      if (this.options2List.length > 1) {
        this.options2List.pop();
        this.value2List.pop();
        this.options3List.pop();
        this.value3List.pop();
      }
    },
    //切换主题
    changeTheme(val) {
      //console.log(val);
      if (val == '转化') {
       //柱形图
        this.initBarOption();
      } else if (val == '转化趋势') {
         //折线图
        this.initOptions();
        if(this.options.length>0){
          this.optionsValue = this.options[0].value;
        }
        this.initLineOption();
      }
      
    },
    initChart() {
      // 通过 echarts.init 方法初始化一个 echarts 实例并通过 setOption 方法生成一个简单的柱状图
      this.chart = echarts.init(document.getElementById("main"));
      // this.chart = echarts.init(this.$el)

      // 使用刚指定的配置项和数据显示图表。
      this.chart.setOption(this.option);
      var thisvue = this;
      this.chart.on('click', function (params) {
    		//console.log(params)
  	      if(params.seriesType== "bar"){
  	        thisvue.toggleMethod2(params.name);//
          }
      });
    },
    getRowClass({ rowIndex }) {
      if (rowIndex == 0) {
        return "background:RGB(254,242,234)";
      } else {
        return "";
      }
    },
  },
  destroyed() {},
};
</script>

<style scoped>
.card1 {
  text-align: left;
  font-size: 18px;
}

.index {
  min-height: 200px;
  padding: 20px;
  background-color: #fff;
  color: #303133;
  text-align: left;
}
.detail {
  padding: 10px 0;
}
.detail2 {
  padding: 10px 0 0 0;
}
.el-divider--horizontal {
  margin: 0;
  margin-bottom: 20px;
}
.card {
  padding: 30px 20px 20px 20px;
  background-color: #fff;
  color: #303133;
  text-align: left;
  font-size: 18px;
  border-right: 1px solid #f7f8fa;
}
.imgr {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  float: right;
  margin-top: 3px;
}
</style>
